class ListingsController < ApplicationController
  def general_search
       if params[:keyword]
                @keyword="@title(#{params[:keyword].to_s}) | @description(#{params[:keyword].to_s})"
    
       else
          @keyword=""
       end
   if params[:cityname]
                @cityname="@cityname(#{params[:cityname].to_s})"

       else
          @cityname=""
       end

     if params[:universityname]
                @universityname="@universityname(#{params[:universityname].to_s})"

       else
          @university=""
       end
     if params[:categoryname]
                @categoryname="@categoryname(#{params[:categoryname].to_s})"

       else
          @categoryname=""
       end


                    params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty?
                     @location=''
                   else
                     @location="@location("+params[:location].to_s+")"
                   end


                        @advertisments = Advertisment.find_with_sphinx("#{@location} #{@keyword} #{@cityname} #{@universityname} #{@categoryname}",  :sphinx => {:mode => :extended, :limit => 1001})
                
                        @advertisments_paginate = Advertisment.find_with_sphinx("#{@location} #{@keyword} #{@cityname} #{@universityname} #{@categoryname}",  :sphinx => {:mode => :extended, :limit => 1001}).paginate :page => params[:page],:per_page => 10
                          @total_ads= @advertisments_paginate.total_entries
                    #@universities= @advertisments.collect{|x| [x.name, x.advertisments.count]}.sort{|x,y| y[1] <=> x[1]}
                          respond_to do |format|
                format.html
                format.js {
                      render :update do |page|
                      page.replace_html 'listings-search-results', :partial => 'general_advertisments'
                      end
                  }
       end


  end

    def city
              @city = City.find_by_stripped_name(params[:city])
              @all_univ = @city.universities
              @popular=@all_univ.collect{|x| [x.name, x.advertisments.count]}.sort{|x,y| y[1] <=> x[1]}
              @universities=University.find(:all,:conditions=>"city_id="+@city.id.to_s)

                 @category = Category.find_by_stripped_name(params[:category])
                 @sub_category_string=@category.sub_categories
                 @sc=''
                 @sub_category_string.each do |sc|
                   @sc= @sc+" "+sc.name.to_s
                 end

                 @university = University.find_by_stripped_name(params[:university])
                 sub_cat= SubCategory.find_by_stripped_name(params[:sub_category])
                 if params[:search]=="Filter"
                   @catch=0
                   @tom=''
                    params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty?
                     location=''
                   else
                     location="@location("+params[:location].to_s+")"
                   end
              if params[:keyword]
                @keyword="@title(#{params[:keyword].to_s}) | @description(#{params[:keyword].to_s})"
                @catch=1
#                @tom="keyword"
              else
                @keyword=''
              end
              if params[:university]
                @university=  "@universityname(#{params[:university]})"
                @catch=1
#                @tom=@tom+", university"
              else
                @university=''
              end
              if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"
                @catch=1
#                @tom=@tom+", sub_category"
              else
                @sub_category=''
              end

                          if @catch==1
#                            @tom=@tom+' ,catch=1'
                            @advertisments = Advertisment.find_with_sphinx(" #{@location} @categoryname(#{@category.name}) #{@keyword} #{@sub_category} @cityname(#{@city.name}) #{@university}", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                          else
                          @advertisments = Advertisment.find_with_sphinx("@categoryname(\"#{@category.name}\") @cityname(\"#{@city.name}\")", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                         end

                 end


               if params[:search]=="True"
                 @catch=0
                 @tom=''
                  params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty?
                     @location=''
                    else
                     @location="@location("+params[:location].to_s+")"
                    end

              if params[:keyword]
                @keyword="@title(#{params[:keyword].to_s}) | @description(#{params[:keyword].to_s})"
                @catch=2
#                @tom="keyword"
              else
                @keyword=''
              end
              if params[:university]
                @university=  "@universityname(#{params[:university]})"
                @catch=2
#                @tom=@tom+", university"
              else
                @university=''
              end
              if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"
                @catch=2
#                @tom=@tom+", sub_category"
              else
                @sub_category=''
              end



                if @catch==2
#                  @tom=@tom+' ,catch=2'

                @advertisments = Advertisment.find_with_sphinx(" #{@location} @categoryname(#{@category.name}) #{@keyword} #{@sub_category} @cityname(#{@city.name}) #{@university}", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                else
                @advertisments = Advertisment.find_with_sphinx("@categoryname(\"#{@category.name}\") @cityname(\"#{@city.name}\")",  :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                end
              params[:keyword] =  (params[:keyword].nil?) ? "" : params[:keyword].strip
              params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty? &&  params[:keyword].empty?
                                      @advertisments = Advertisment.find_with_sphinx("@categoryname(\"#{@category.name}\") @cityname(\"#{@city.name}\")",  :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10

                    end
              end
              if params[:search]!="True" &&  params[:search]!="Filter"
               
                if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"

              else
                @sub_category=''
              end
                @advertisments = Advertisment.find_with_sphinx("@categoryname(#{@category.name}) #{@sub_category} @cityname(#{@city.name})", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10

                end
                 @total_ads= @advertisments.total_entries


                respond_to do |format|
                format.html
                format.js {
                      render :update do |page|
                      page.replace_html 'listings-search-results', :partial => 'advertisments'
                      end
                  }
       end
       @tom="tomchy"

  end

        def index
#              @city = City.find_by_stripped_name(params[:city])
#              @all_univ = @city.universities
#              @popular=@all_univ.collect{|x| [x.name, x.advertisments.count]}.sort{|x,y| y[1] <=> x[1]}
#              @universities=University.find(:all,:conditions=>"city_id="+@city.id.to_s)

                 @category = Category.find_by_stripped_name(params[:category])
                 @sub_category_string=@category.sub_categories
                 @sc=''
                 @sub_category_string.each do |sc|
                   @sc= @sc+" "+sc.name.to_s
                 end

                 @university = University.find_by_stripped_name(params[:university])
                 sub_cat= SubCategory.find_by_stripped_name(params[:sub_category])
                 if params[:search]=="Filter"
                   @catch=0
                   @tom=''
                    params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty?
                     location=''
                   else
                     location="@location("+params[:location].to_s+")"
                   end
              if params[:keyword]
                @keyword="@title(#{params[:keyword].to_s}) | @description(#{params[:keyword].to_s})"
                @catch=1
#                @tom="keyword"
              else
                @keyword=''
              end
              if params[:university]
                @university=  "@universityname(#{params[:university]})"
                @catch=1
#                @tom=@tom+", university"
              else
                @university=''
              end
              if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"
                @catch=1
#                @tom=@tom+", sub_category"
              else
                @sub_category=''
              end

                          if @catch==1
#                            @tom=@tom+' ,catch=1'
                            @advertisments = Advertisment.find_with_sphinx(" #{@location} @categoryname(#{@category.name}) #{@keyword} #{@sub_category} @cityname(#{@city.name}) #{@university}", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                          else
                          @advertisments = Advertisment.find_with_sphinx("@categoryname(\"#{@category.name}\") @cityname(\"#{@city.name}\")", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                         end

                 end


               if params[:search]=="True"
                 @catch=0
                 @tom=''
                  params[:location] =  (params[:location].nil?) ? "" : params[:location].strip
                    if params[:location].empty?
                     @location=''
                    else
                     @location="@location("+params[:location].to_s+")"
                    end

              if params[:keyword]
                @keyword="@title(#{params[:keyword].to_s}) | @description(#{params[:keyword].to_s})"
                @catch=2
#                @tom="keyword"
              else
                @keyword=''
              end
              if params[:university]
                  @tom="ddd"
                @university=  "@universityname(#{params[:university]})"
                @catch=2
#                @tom=@tom+", university"
              else
                @university=''
              end
              if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"
                @catch=2
#                @tom=@tom+", sub_category"
              else
                @sub_category=''
              end



                if @catch==2
#                  @tom=@tom+' ,catch=2'

                @advertisments = Advertisment.find_with_sphinx(" #{@location} @categoryname(#{@category.name}) #{@keyword} #{@sub_category} @cityname(#{@city.name}) #{@university}", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                else
                
                @advertisments = Advertisment.find_with_sphinx("@categoryname(\"#{@category.name}\") @cityname(\"#{@city.name}\")",  :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10
                end

              end
              if params[:search]!="True" &&  params[:search]!="Filter"

                if params[:sub_category]
                @sub_category=  "@subcategorystrippedname(\"#{params[:sub_category]}\")"

              else
                @sub_category=''
              end
                @advertisments = Advertisment.find_with_sphinx("#{@university})", :sphinx => {:mode => :extended, :limit => 1500}).paginate :page => params[:page],:per_page => 10

                end

                @total_ads= @advertisments.total_entries
                respond_to do |format|
                format.html
                format.js {
                      render :update do |page|
                      page.replace_html 'listings-search-results', :partial => 'advertisments'
                      end
                  }
       end

                         
@tom=1

  end

#   def index
#
#       @category = Category.find_by_stripped_name(params[:category])
#       if params[:sub_category]
#         id= SubCategory.find_by_stripped_name(params[:sub_category]).id
#       else
#         id = @category.sub_categories
#       end
#
#       @university = University.find_by_stripped_name(params[:university])
#       @advertisments = @category.advertisments.paginate(:page =>params[:page],:per_page => 10,:order=>"created_at desc",:conditions =>{ :sub_category_id => id , :university_id => @university.id})
#       @total_ads= @advertisments.total_entries
#
##       if @featured_advertisments
##       @attachment=Attachment.find_by_advertisment_id(@featured_advertisments)
##       end
##       if @attachment
##       @image=@attachment.file
##       else
##         @image=''
##       end
#       @sub_category=SubCategory.find_by_category_id(@category.id)
#       @sub_category_fields=@sub_category.advertisment_form_field
#      # @attribute_fields=@sub_category.advertisments.advertisment_attribute_field_values.find(:all)
#       @attribute_fields=AdvertismentAttributeFieldValue.find_by_advertisment_id(@advertisments)
#      # @attribute_fields=@category.advertisments.advertisment_attribute_field_values.find(:all)
#
#        respond_to do |format|
#        format.html
#        format.js {
#                      render :update do |page|
#                      page.replace_html 'listings-search-results', :partial => 'advertisments'
#                      end
#                  }
#       end
#
#
#
#
# end




  def search

          @original_category=params[:category]
          @original_sub_category=(params[:sub_category])
          @original_university = (params[:university])
          @location=params[:location]
          search_term = params[:keyword]
          @search_term=search_term
          @category = Category.find_by_stripped_name(params[:category])
          @sub_category=SubCategory.find_by_stripped_name(params[:sub_category])

          if params[:university]
            @university = University.find_by_stripped_name(params[:university])
            @university_condition=" university_id="+@university.id.to_s
          else
            @city = City.find_by_stripped_name(params[:city])
            @universities   = @city.universities
            @university_ids = @universities.collect {|university| university.id}
            @university = @universities[0]
            @university_condition ="1=1"
          end
          if (params[:sub_category])
            @sub_category_condition="sub_category_id="+@sub_category.id.to_s+" and "
          else
             @sub_category=SubCategory.find(:first,:conditions=>"category_id="+@category.id.to_s)
             @sub_category_condition="sub_category_id="+@sub_category.id.to_s+" and "
          end

          if (params[:keyword])
            search_term = search_term.split(" ").collect{|x| "title like '%#{x}%' or description like '%#{x}%' "}.join(" or ")
            @search_term1 = "("+ search_term + ") and ("+@sub_category_condition+" "+@university_condition+"  and location like '%"+@location.to_s+"%')"
          else
            @search_term1 = "sub_category_id="+@sub_category_condition+" "+@university_condition+"  and location like '%"+@location.to_s+"%'"
          end

          @advertisments =@city.search_advertisments( params[:keyword]).paginate :page => params[:page],:per_page => 10
#@advertisments2 = @city.search_advertisments( params[:keyword])
@total_ads = @advertisments.total_entries

    respond_to do |format|
                format.html
                format.js {
                    render :update do |page|
                    page.replace_html 'listings-search-results-cap', :partial => 'search_results'
                    end
                 }
              end
  end

    def filtered_advertisments

           @filtered_advertisments= params[:advertisments].split("-")
           @category = Category.find_by_stripped_name(params[:category])
           id = @category.sub_categories
           @university = University.find_by_stripped_name(params[:university])
           @advertisments = Advertisment.find(@filtered_advertisments).paginate(:page =>params[:page],:per_page => 10,:order=>"created_at desc",:conditions =>{ :sub_category_id => id , :university_id => @university.id})
           @total_ads=@advertisments.total_entries

    #       if @featured_advertisments
    #       @attachment=Attachment.find_by_advertisment_id(@featured_advertisments)
    #       end
    #       if @attachment
    #       @image=@attachment.file
    #       else
    #         @image=''
    #       end
           @sub_category=SubCategory.find_by_category_id(@category.id)
           @sub_category_fields=@sub_category.advertisment_form_field
          # @attribute_fields=@sub_category.advertisments.advertisment_attribute_field_values.find(:all)
           @attribute_fields=AdvertismentAttributeFieldValue.find_by_advertisment_id(@advertisments)
          # @attribute_fields=@category.advertisments.advertisment_attribute_field_values.find(:all)

            respond_to do |format|
            format.html
            format.js {
                          render :update do |page|
                          page.replace_html 'listings-search-results', :partial => 'advertisments'
                          end
                      }
             end

    end

    def save_advertisment
           @advertisment           = Advertisment.find(params[:id])
              if session[:user]
                 @user_id                = session[:user][:id]
                 @bookmarks          = BookmarkedAd.find(:all, :conditions=>"user_id='"+@user_id.to_s+"'")
              end
               render :layout => false
    end

    def insert_ads
          @advertisments = Advertisment.find(:all,:limit => 10)
          @tags = Tag.find(:all)
          @tagcloud = Hash.new
          @tags.each do |t|
                  @result=t.name.split(",")
                  @result.each do |tags|
                  @tagcloud[tags]
                        if(@tagcloud[tags].nil?)
                                  @tagcloud[tags]=1
                        else
                                  @tagcloud[tags]=@tagcloud[tags]+1
                        end
                   end
          end
          @maxsize = 40;
          @minsize = 10;
          @maxval = @tagcloud.values.max
          @minval = @tagcloud.values.min
          @spread = @maxval - @minval;
          @step = ((@maxsize - @minsize)*15) / (@spread);
    end

    def bookmark_ad
          @user_id = session[:user][:id]
          @advertisment = Advertisment.find_by_id(params[:id])
          @folder = params[:bookmark][:folder]
          #@event_id = params[:event]
          if request.post?
              @bookmark = BookmarkedAd.new(:folder=>@folder,:user_id=>@user_id,:advertisment_id=>@advertisment.id)
              @bookmark.save
              redirect_to :action=>"show", :id=>params[:id]
              flash[:message]="Advertisment Saved Successfully"
          end


    end
    def invite_friends
    #@user = User.find(params[:id])
    end

    def import
    #@users = User.find(params[:id])
        begin
        @sites = {"gmail"  => Contacts::Gmail, "yahoo" => Contacts::Yahoo, "hotmail" => Contacts::Hotmail}
        @contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
        #@users , @no_users = [], []
        #@contacts.each do |contact|
        #if u = User.find(:first , :conditions => @users.email = ‘#{contact[1]}’ , :include =>[:user])
        #if u = User.find(:first , :conditions => "email = '#{contact[1]}'" )
        #@users << u
        #else
        #@no_users << {:name => contact[0] , :email => contact[1]}
        #end
        #end
            respond_to do |format|
            format.html {render :template => 'shared/_contact_list', :layout => false}
            format.xml {render :xml => @contacts.to_xml}
            end
        end

    end
end
